<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .list {
            width: 200px;
            height: 150px;
            background-color: skyblue;
            overflow: auto;
        }
        .news {
            height: 30px;
        }
    </style>
</head>
<body>
<div id="React"></div>

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<!-- jsx转为js -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

<script type="text/babel">

    class NewsList extends React.Component {

        // 初始化状态
        state = {newsArr: []}

        componentDidMount() {
            setInterval(() => {
                let {newsArr} = this.state
                const news = "新闻" + (newsArr.length + 1)
                this.setState({newsArr: [news, ...newsArr]});
            }, 1000)
        }

        // 加1按钮回调
        add = () => {
            let {count} = this.state
            this.setState({count: count + 1})
        }

        death = () => {
            ReactDOM.unmountComponentAtNode(document.getElementById("React"))
        }

        // 强制更新按钮回调
        force = () => {
            this.forceUpdate()
        }

        constructor(props) {
            super(props);
            console.log("1构造器")
        }

        render() {
            let {count} = this.state
            console.log("render")
            return (
                    <div className="list" ref="list">
                        {
                            this.state.newsArr.map((n, index) => {
                                return <div key={index} className="news">{n}</div>
                            })
                        }
                    </div>
            )
        }

        // 更新前获取快照值
        getSnapshotBeforeUpdate() {
           return this.refs.list.scrollHeight
        }

        // 组件更新完毕
        componentDidUpdate(prevProps, prevState, height) {
            this.refs.list.scrollTop += this.refs.list.scrollHeight - height
        }
    }



    ReactDOM.render(<NewsList count={199}/>, document.getElementById("React"))
</script>
</body>
</html>